/** author wanghua
 *  date   2014-6
*/
/**树形下拉选项
 * 传入的input定义为 code_input，其value值为代码
 * dkSelectTree会在code_input后面添加一个新的input，定义为name_input
 * dkSelectTree会将code_input的id，name,value属性赋值给name_input，并将code_input的id，name清空
 * 树形下拉菜单中的选中项的code，name将分别存放在code_input，name_input的value属性中
 * 即最后仍然从传入的input（code_input）的value属性中获取选中值。
 * 如果是多选，多个选中值用 | 做分割。
 * 
 * 在一个input元素下显示一个树形选择列表，树形中的选中值仍然放到input的value中，此input会被设置为display:none。
 * 会另外
 * 
 * 注意：tree重新初始化用 reLoadData(url) 方法

例子：
$("#districtCode").dkSelectTree({
			url:"rest/base/glRoadinfoHandler/getDistricts",//一次获取全部节点
			listType:"tree", //tree or list
			multiSelect:false,
			Async:false,
			width : 200
});
*/
/*setting = { 
	idField,  //默认值：id
	pidField, //默认值： pId
	nameField,//默认值: name
	url,//获取数据的url
	multiSelect,单选还是多选，默认 false	
	listType:'tree', //默认值 tree  可选值list
	Async:true, //树节点是否异步加载 
	asyncAutoParam,  //异步加载时需要自动提交父节点属性的参数。[setting.async.enable = true 时生效]默认值：[ ],,,1、将需要作为参数提交的属性名称，制作成 Array 即可，例如：["id", "name"]  2、可以设置提交时的参数名称，例如 server 只接受 zId : ["id=zId"]
	width,
	height,
	onSelect(id,name)
	onSuccess(event, treeId, treeNode, msg)
}


		
前提：（在不显示树形结构时，隐藏前面的空白区域）
	修改ztree 在init函数中增加
	if(setting.view.showLine == false){
				consts.className.SWITCH = "switch_z";
	}
	在zTreeStyle.css 文件中增加 .ztree li span.button.switch_z {width:1px; height:18px}
 
 */
(function($) {
	$.fn.dkSelectTree=function(setting){
		var self = this;
		self.splitChar = '|';
		self.setting = setting;
		if(setting.splitChar){
			self.splitChar = setting.splitChar;
		}
		self.inputElement = $(this); //需要下拉列表的input的id
		
		var elementId = $(this).attr("id");
		var elementName = $(this).attr("name");
		var elementValue = $(this).val();
		
		self.orgnElementId = elementId;
		self.newElementId = elementId+"_of_replace_id";
		$(this).bind("keydown",inputSetReadonly);

		var input2Html = "<input type='text' style='display:none' id='"+elementId+"' name='"+elementName+"' value='"+elementValue+"'/>";

		$(this).attr("id",self.newElementId);
		$(this).attr("name",self.newElementId);
		$(this).attr("ignorePost",true);			
		$(input2Html).insertAfter($(this));

		self.setting.idInput = elementId;
		self.idInput = $("#"+elementId);
		if(!self.setting.idInput || self.setting.idInput=='' || self.idInput.length==0){
			alert('dkSelectTree:请设置'+$(this).attr('id')+'对应的id Input值');
			return null;
		}
		self.elementId = null;
		self.treeId = null;
		self.ztree = null;
		self.treeContId = null;
		if(self.setting.listType != 'list'){
			self.setting.listType = 'tree';
		}
		/**
		 * 创建div，并绑定事件
		 */
		var _createTree = function(element, treeContId, treeId, width, height){			
			var pElement = element;//弹出下拉列表的input
			var elementId = pElement.attr("id");//input.id
			 
			var pElementWidth = pElement.outerWidth();
			
			var treeWidth = pElementWidth;
			var treeHeight = 200;
			 
			if(width && width>pElementWidth){
				treeWidth = width;
			}
			if(height && height>1){
				treeHeight = height;
			}
			
			var position = pElement.css("position");
		    var loadingDivId = treeContId+"_loading";
			var treeDivHtml = "<div id='{treeContId}' style='position:absolute;display:none;z-index:100;width: {width}px; height: {height}px;' >";
			treeDivHtml = treeDivHtml + "<ul id='"+loadingDivId+"' class='l-loading'></ul><ul id='{id}' style='height:98%' class='ztree'></ul>";
			//alert(treeDivHtml);
			treeDivHtml = treeDivHtml.replace("{treeContId}",treeContId);
			treeDivHtml = treeDivHtml.replace("{id}",treeId);
			treeDivHtml = treeDivHtml.replace("{width}",treeWidth);
			treeDivHtml = treeDivHtml.replace("{height}",treeHeight); 
			treeDivHtml = treeDivHtml+"</div>";
			
			var treeDiv = $(treeDivHtml).addClass("dkSelectTreeCont").appendTo(pElement.parent()); 
			
			_resize();
//			var outerWidth = pElement.outerWidth(); //input的内宽
//			var innerWidth = pElement.innerWidth(); //input的外宽
//			var leftMargin = (outerWidth - innerWidth) / 2; //input的左边距
//			
//			var outerHeight = pElement.outerHeight(); //input的内宽
//			var innerHeight = pElement.innerHeight(); //input的外宽
//			var topMargin = (outerHeight - innerHeight) / 2; //input的左边距
//
//			var elementTop = pElement.position().top;
//			var elementLeft = pElement.position().left;
//			elementTop += pElement.outerHeight()+topMargin;
//
//			treeDiv.css("top" , elementTop);
//			treeDiv.css("left", elementLeft + leftMargin);
			
			var tree_ul = $('#'+treeId);
			treeDiv.bind("mouseover",treeContentMouseOver);
			treeDiv.bind("mouseenter",treeContentMouseEnter);
			treeDiv.bind("mouseleave",treeContentMouseOut);
			
			treeDiv.bind("blur",treeContentBlur);

			$(document).click(function (e) {
				documentOnClick();
			});
		};
		
		var _resize = function(){
			treeDiv = $("#"+self.treeContId);
			pElement = self.inputElement;
			var outerWidth = pElement.outerWidth(); //input的内宽
			var innerWidth = pElement.innerWidth(); //input的外宽
			var leftMargin = (outerWidth - innerWidth) / 2; //input的左边距
			
			var outerHeight = pElement.outerHeight(); //input的内宽
			var innerHeight = pElement.innerHeight(); //input的外宽
			var topMargin = (outerHeight - innerHeight) / 2; //input的左边距
			
			var elementTop = pElement.position().top;
			var elementLeft = pElement.position().left;
			elementTop += pElement.outerHeight()+topMargin;

			treeDiv.css("top" , elementTop);
			treeDiv.css("left", elementLeft + leftMargin);
		};
		/**
		 * 创建tree
		 */
		var _initList = function(){			
			if(self.ztree != null)return;
			  
			self.treeContId = self.orgnElementId+"_ztree_cont_wh";
			self.treeId = self.orgnElementId+"_ztree_wh";
			
			var jqtreeId = "#"+self.treeId;
			self.jqtreeId = jqtreeId;
			self.idField = self.setting.idField || 'id';
			self.pidField = self.setting.pidField || 'pId';
			self.nameField =  self.setting.nameField || 'name';
			self.url = self.setting.url;
			var multiSelect = self.setting.multiSelect || false;
			
			_createTree(self.inputElement, self.treeContId, self.treeId, self.setting.width, self.setting.height);
			
			
			var tree_setting = {
				async: {
					enable: true,
					url:self.url,
					autoParam: self.setting.asyncAutoParam
				},
				data:{
					key:{
						name:self.nameField
					},
					simpleData:{
						enable:true,
						idKey:self.idField,
						pIdKey:self.pidField
					}
				},
				view:{
					showIcon:false,
					showLine:false
				},
				check:{
					enable:true,
					chkboxType: { "Y": "s", "N": "ps" }
				},
				callback:{ 
					onAsyncSuccess: onTreeAsyncSuccess,
					beforeAsync: beforeTreeNodeAsync
				}
			};
			if(self.setting.listType == 'tree'){
				tree_setting.view.showIcon = true;
				tree_setting.view.showLine = true;
			}
			if(self.setting.multiSelect){
				tree_setting.check.enable = true;
				tree_setting.callback.onCheck = treeNodeOnCheck;
			}else{
				tree_setting.check.enable = false;
				tree_setting.callback.onClick = treeNodeOnClick;
			}
			
			self.tree_setting = tree_setting;

			self.ztree = $.fn.zTree.init($(jqtreeId), tree_setting);
			 
		};
		
		var reLoadData = function(url){
			//var tree_setting = self.tree_setting;
			//tree_setting.async.url = url;
			//self.ztree.destroy();
			//self.ztree = $.fn.zTree.init($(self.jqtreeId), tree_setting);	
			
			var setting = self.ztree.setting;
			setting.async.url = url;
			self.setting.AsyncCount = 0;
			self.ztree.reAsyncChildNodes(null,"refresh");
		};
		
		self.setting.AsyncCount=0;
		var beforeTreeNodeAsync = function(treeId, treeNode) {
			self.setting.AsyncCount = self.setting.AsyncCount + 1;
			if(self.setting.Async == false && self.setting.AsyncCount>1)
			{
				return false;
			}
		};
		 
		var onTreeAsyncSuccess = function(event, treeId, treeNode, msg) {
			var loadingDivId = self.treeContId+"_loading";
			$("#"+loadingDivId).css("display","none");
		   
			if(self.setting.listType != 'tree'){ 
				$('.span.button.switch',$("#"+self.treeContId)).css('width', '1');
			};
			setDefaultText();
			apply(self.setting.onSuccess, [event, treeId, treeNode, msg]);//by lkk
		};
		/**选中节点*/
		var treeNodeOnCheck = function(event, treeId, treeNode){
			 var ids = "";
			 var names = "";			 
			 var nodes = self.ztree.getCheckedNodes(true);			 
			 for(var i=0;i<nodes.length;++i){
				 var node = nodes[i];
				 var id = node[self.idField];
				 var name = node[self.nameField];
				 ids += id+self.splitChar;
				 names += name+self.splitChar;
			 }
			 if(names.length>0) names = names.substring(0, names.length-1);
			 if(ids.length>0) ids = ids.substring(0, ids.length-1);
			 self.inputElement.val(names); //需要下拉列表的input的id
			 self.idInput.val(ids);//隐藏域
			 apply(self.setting.onSelect, [id,name,self.orgnElementId]);
		};
		
		/**根据隐藏域的值设置显示域的值*/
		var setDefaultText = function(){
			var nodes = self.ztree.transformToArray(self.ztree.getNodes());
			var names = "";	
			
			var ids = self.splitChar+self.idInput.val()+self.splitChar;
			for(var i=0;i<nodes.length;++i){
				 var node = nodes[i];
				 var id = node[self.idField];
				 var name = node[self.nameField];
				 var idtag = self.splitChar+id+self.splitChar;
				 if(ids.indexOf(idtag)>=0){//隐藏域中的id包含node中的id
					 names += name+self.splitChar;
					 if(self.ztree.setting.check.enable){
						 self.ztree.checkNode(node,true,false);
						 self.ztree.selectNode(node,false);
						 if(node.getParentNode()){
							 self.ztree.expandNode(node.getParentNode(),true,false,true);
						 }						 
					 }else{
						 self.ztree.selectNode(node,false);
						 if(node.getParentNode()){
							 self.ztree.expandNode(node.getParentNode(),true,false,true);
						 }
					 }
				 }				
			}
			if(names.length>0) names = names.substring(0, names.length-1);
			
			self.inputElement.val(names); //需要下拉列表的input的id
		};
		/**给控件设置新的值（id）*/
		var setValue = function(idValue){
			var nodes = self.ztree.transformToArray(self.ztree.getNodes());
			var names = "";
			var ids = self.splitChar+idValue+self.splitChar;
			for(var i=0;i<nodes.length;++i){
				 var node = nodes[i];
				 var id = node[self.idField];
				 var name = node[self.nameField];
				 var idtag = self.splitChar+id+self.splitChar;
				 if(ids.indexOf(idtag)>=0){
					 names += name+self.splitChar;
				 }
			}
			if(names.length>0) names = names.substring(0, names.length-1);
			self.inputElement.val(names); //需要下拉列表的input的id
			self.idInput.val(ids);//给隐藏域设置值
		};
		
		/**选择节点*/
		//var treeNodeClickEvent = false;
		var treeNodeOnClick = function(event, treeId, treeNode, clickFlag){
			var id = treeNode[self.idField];
			var name = treeNode[self.nameField];
			
			self.inputElement.val(name); //需要下拉列表的input的id
			self.idInput.val(id);//给隐藏域设置值
			setListVisible(false);
			//treeNodeClickEvent = true;
			//self.inputElement.focus();
			
			apply(self.setting.onSelect,[id,name,self.orgnElementId]);
		};
		
		var apply = function(fun, param){			
			if ((typeof fun) == "function") {				 
				return fun.apply(this,param);
			}
		};
		
		var setListVisible = function(visible){
			//console.log('list visible:'+visible);
			if(visible){
				$("#"+self.treeContId).css("display","block");
			}else{
				$("#"+self.treeContId).css("display","none");
			}
		};
				
		var _init = function(){
			if(self.inputElement.attr("dkSelectTree") == "true"){
				return;
			}			
			self.inputElement.attr("dkSelectTree","true");
			self.inputElement.bind("keydown",inputSetReadonly);
			self.inputElement.bind("paste",function(){return false;});
			self.inputElement.bind("cut",function(){return false;});
			self.inputElement.bind("focus",{},inputOnFocus);
			self.inputElement.bind("click",{},inputClick);
			self.inputElement.bind("blur",{},inputOnBlur);
			if(!self.setting.lazyLoad){
				_initList();
			}
		};
		
		var inputSetReadonly = function(e){			
			if(event.keyCode >0)return false;
		};
		
		var inputOnFocus = function(){
			if(self.ztree == null){			 
				_initList();
			}
			_resize();
			//console.log("treeNodeClickEvent:"+treeNodeClickEvent);
			//if(!treeNodeClickEvent){				
				setListVisible(true);
			//}
			//treeNodeClickEvent = false;
		};
		
		self.mouseIntreeContent = false;
		var treeContentMouseOver = function (){
			self.mouseIntreeContent = true;
		};
		
		var treeContentMouseEnter = function (){
			self.mouseIntreeContent = true;
			//console.log('treeContentMouseEnter');
		};
		
		var treeContentMouseOut = function (){
			self.mouseIntreeContent = false;
			//console.log('treeContentMouseOut');
		};
		
		/**
		 * 页面任意位置的点击事件
		 */
		var documentOnClick = function(e){
			if(document.activeElement){
			//console.log('documentOnClick....');
			var activeId = document.activeElement.id;
			
			if(!self.mouseIntreeContent && activeId != self.newElementId){
				setListVisible(false);
			}}
		};
		
		/** 列表div失去焦点时触发，隐藏列表 */
		var treeContentBlur = function(event) {
			//console.log('treeContentBlur');
			setListVisible(false);
		};
		
		/** input失去焦点时触发 */
		var inputOnBlur = function(event){				
			if(self.mouseIntreeContent){ //input失去焦点时，如果鼠标还在列表div内，则仍然显示列表
				return;
			}
			//input失去焦点时，如果鼠标已经不在列表div内了，则隐藏列表
			setListVisible(false);
		};
		
		var inputClick = function(e){
			//return false; //阻止冒泡执行document.click事件
			//不能return false，否则如果有两个dkSelectTree的时候，会出现两个下拉列表同时显示的问题（在第一个下拉列表获取焦点的情况下，在点击第二个下拉列表输入框）
			//在documentOnClick中判断是否点击的本身的input
		};
		
		self.setDefaultText = setDefaultText;
		self.refresh = setDefaultText;
		self.setValue = setValue;
		self.reLoadData = reLoadData;
		var dkSelectTree ={
			self:self,
			test : function(){
				//alert(self.inputElement.attr("id"));
			},
			setSplitChar : function(char){
				self.splitChar  = char;
			},
			setDefaultText : function(){
				self.setDefaultText();
			},
			refresh : function(){
				self.setDefaultText();
			},
			setValue : function(value){
				self.setValue(value);
			},
			reLoadData:function(url){
				self.reLoadData(url);
			}
		};
		
		_init();
		
		
		return dkSelectTree;
	};	
})(jQuery);